#include "Inf_DHT11.h"

/* 发送起始信号 */
static void Inf_DHT11_Start(void)
{
    HAL_GPIO_WritePin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin, GPIO_PIN_RESET);
    Common_Delay_us(20000);
    HAL_GPIO_WritePin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin, GPIO_PIN_SET);
    Common_Delay_us(30);
}

/* 等待DHT11的回应 */
uint8_t Inf_DHT11_Check(void) 	   
{   
	uint8_t retry=0; 
    //DHT11会拉低40~80us
    while (HAL_GPIO_ReadPin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin) && retry < 100)
	{
		retry++;
		Common_Delay_us(1);
	}
	if(retry >= 100) return 1;
	else retry=0;
    //DHT11拉低后会再次拉高40~80us
    while (!HAL_GPIO_ReadPin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin) && retry < 100)
	{
		retry++;
		Common_Delay_us(1);
	}
	if(retry >= 100) return 1;	    
	return 0;
}

/* 从DHT11读取一个位 */
static uint8_t Inf_DHT11_ReadBit(void) 			 
{
 	uint8_t retry=0;
	while(HAL_GPIO_ReadPin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin) && retry < 100)//等待变为低电平
	{
		retry++;
		Common_Delay_us(1);
	}
	retry=0;
	while(!HAL_GPIO_ReadPin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin) && retry < 100)//等待变高电平
	{
		retry++;
		Common_Delay_us(1);
	}
	Common_Delay_us(40);//等待40us
	if(HAL_GPIO_ReadPin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin)) return 1;
	else return 0;		   
}

/* 从DHT11读取一个字节 */
static uint8_t Inf_DHT11_ReadByte(void)    
{        
	uint8_t dat = 0;
	for (uint8_t i = 0; i < 8; i++) 
	{
		dat<<=1; 
        dat |= Inf_DHT11_ReadBit();
	}						    
	return dat;
}

void Inf_DHT11_Init(void)
{
    HAL_GPIO_WritePin(DHT11_DATA_GPIO_Port, DHT11_DATA_Pin, GPIO_PIN_SET);
    HAL_TIM_Base_Start(&htim2);
}

int8_t Inf_DHT11_ReadTemperature(uint8_t *humidity, float *temperature)
{
    uint8_t data[5] = {0};
    Inf_DHT11_Start();
    if(Inf_DHT11_Check()) return -1;
    for (uint8_t i = 0; i < 5; i++)
    {
        data[i] = Inf_DHT11_ReadByte();
    }
    if(data[0] + data[1] + data[2] + data[3] == data[4])
    {
        *humidity = data[0];
        *temperature = data[2] + data[3] / 10.0;
        return 0;
    }
    return -1;
}
